package com.framework.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.framework.dao.DistribuDao;
import com.framework.entity.sys.SysAgent;
import com.framework.entity.ter.TerDistribu;
import com.framework.entity.ter.TerTerminalInfo;
import com.framework.exception.RRException;
import com.framework.exception.menu.RespCode;
import com.framework.service.AgentService;
import com.framework.service.DistribuService;
import com.framework.service.TerFlowInfoService;
import com.framework.service.TerRebackMerLogService;
import com.framework.validator.Assert;
import com.framework.view.DisRecordDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Service("distribuService")
public class DistribuServiceImpl extends ServiceImpl<DistribuDao, TerDistribu> implements DistribuService {
    @Autowired
    private TerRebackMerLogService terRebackMerLogService;

    @Autowired
    private AgentService agentService;

    @Autowired
    private TerFlowInfoService terFlowInfoService;

    @Override
    public Long queryTerminalOwn(String sn) {
        Assert.isBlank(sn, "终端SN不能为空");
        TerDistribu terDistribu = new TerDistribu();
        terDistribu.setSn(sn);
        terDistribu.setState(2);
        TerDistribu t = baseMapper.selectOne(terDistribu);
        if (t == null) {
            return null;
        } else {
            Long agentId = t.getAgentId();
            return agentId;
        }
    }

    @Override
    public List<DisRecordDto> queryDisRecordList(String sn) {
        Assert.isBlank(sn, "终端SN不能为空");
        return baseMapper.queryDisRecordList(sn);
    }

    @Override
    public TerDistribu queryDistribu(String sn, Long agentId) {
        TerDistribu d = new TerDistribu();
        d.setSn(sn);
        d.setAgentId(agentId);
        d.setState(2);
        return baseMapper.selectOne(d);
    }

    @Override
    public void insertDistribu(String sn, Long agentId, Long acceptId) {
        TerDistribu dis = queryDistribu(sn, agentId);
        if (dis == null) {
            throw new RRException(RespCode.NOT_PARAM_ERROR);
        }
        baseMapper.updateDistState(dis.getDistribuId(), acceptId);
        TerDistribu d = new TerDistribu();
        d.setState(2);
        d.setAgentId(acceptId);
        d.setSn(sn);
        d.setReceiveState(1);
        d.setDistribuTime(new Date());
        d.setDeptId(dis.getDeptId());
        baseMapper.insert(d);
    }

    @Override
    public void updateAccept(String sn, Long agentId) {
        TerDistribu dis = queryDistribu(sn, agentId);
        if (dis == null) {
            throw new RRException("9000", "未查询到终端分配表信息");
        }
        dis.setReceiveState(2);
        baseMapper.updateAccept(dis.getDistribuId());
    }

    @Override
    public void rebackTerminal(String sn, Long agentId) {

        TerDistribu dis = queryDistribuByAgentId(sn, agentId);
        if (dis == null) {
            return;
        }

        baseMapper.deleteById(dis.getDistribuId());
        if (dis.getToAid() != null) {
            dis = queryDistribuByAgentId(sn, dis.getToAid());
            System.out.println(sn);
            rebackTerminal(sn, dis.getAgentId());

        }
    }

    @Override
    public TerDistribu queryDistribuByAgentId(String sn, Long agentId) {
        TerDistribu distribu = new TerDistribu();
        distribu.setSn(sn);
        distribu.setAgentId(agentId);
        return baseMapper.selectOne(distribu);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void disTerminal(String sn, Long agentId, Long deptId) {
        TerDistribu terDistribu = new TerDistribu();
        terDistribu.setState(2);
        terDistribu.setSn(sn);
        terDistribu = baseMapper.selectOne(terDistribu);
        if (terDistribu == null) {
            throw new RRException("9000", "未查询到该机器的归属人");
        }
        //该机器已经归属于该合伙人，则不进行下面的操作
        if (terDistribu.getAgentId().equals(agentId)) {
            return;
        }

        terDistribu.setState(1);
        terDistribu.setToAid(agentId);
        terDistribu.setReceiveState(1);
        baseMapper.updateById(terDistribu);
        TerDistribu d = new TerDistribu();
        d.setState(2);
        d.setAgentId(agentId);
        d.setSn(sn);
        d.setReceiveState(1);
        d.setDistribuTime(new Date());
        d.setDeptId(deptId);
        baseMapper.insert(d);

    }

    @Override
    public void receiveTerminal() {
        List<TerDistribu> list = baseMapper.queryUnRecieveteList();

        for (TerDistribu terDistribu : list) {
            terDistribu.setReceiveState(2);
            baseMapper.updateById(terDistribu);
        }
    }

    @Override
    public void rebackTerminalToUpper(String sn, Long agentId) {

        System.out.println(sn + "----------" + agentId);

        TerDistribu distribu = selectOne(new EntityWrapper<TerDistribu>().eq("agent_id", agentId).eq("sn", sn).eq("state", 2));
        if (distribu != null) {

            List<TerDistribu> distribus = selectList(new EntityWrapper<TerDistribu>().eq("sn", sn).eq("to_aid", agentId).orderBy("distribu_time", true));
            TerDistribu temp = distribus.get(distribus.size() - 1);

            SysAgent agent = agentService.queryBasicAgentBydeptId(temp.getDeptId());
            Long rebackId = temp.getAgentId();

            if (!temp.getAgentId().equals(agent.getAgentId())) {
                distribu.setToAid(rebackId);
                distribu.setState(1);
                distribu.setReceiveState(1);
                updateById(distribu);

                TerDistribu newDis = new TerDistribu();
                newDis.setDistribuTime(new Date());
                newDis.setReceiveState(2);
                newDis.setState(2);
                newDis.setAgentId(rebackId);
                newDis.setDeptId(distribu.getDeptId());
                newDis.setSn(sn);
                insert(newDis);
                terFlowInfoService.addDisReportInfo(sn, agent.getDeptId(), agentService.queryAgentById(rebackId));
            } else {
                rebackId = agentId;
            }

            terRebackMerLogService.addNewRecord(sn, rebackId);

        }
    }

    @Override
    public void handleDistribu(List<TerTerminalInfo> terminalList, Long agentId, Long deptId) {
        TerTerminalInfo terTerminalInfo;
        TerDistribu terDistribu;
        for (int i = 0; i < terminalList.size(); i++) {
            terTerminalInfo = terminalList.get(i);
            terDistribu = queryDistribuBySn(terTerminalInfo.getSn());
            terDistribu.setToAid(agentId);
            terDistribu.setState(1);
            terDistribu.setReceiveState(1);
            baseMapper.updateById(terDistribu);
            terDistribu = new TerDistribu();
            terDistribu.setDeptId(deptId);
            terDistribu.setReceiveState(2);
            terDistribu.setState(2);
            terDistribu.setAgentId(agentId);
            terDistribu.setDistribuTime(new Date());
            terDistribu.setSn(terTerminalInfo.getSn());
            baseMapper.insert(terDistribu);
        }


    }

    private TerDistribu queryDistribuBySn(String sn) {
        TerDistribu dis = new TerDistribu();
        dis.setSn(sn);
        dis.setState(2);
        return baseMapper.selectOne(dis);
    }


    @Override
    public void insertDisList(List<TerTerminalInfo> terlist, Long agentId) {
        List<TerDistribu> distribus = new ArrayList<>();
        TerDistribu terDistribu;
        for (TerTerminalInfo info :terlist) {
            terDistribu = new TerDistribu();
            terDistribu.setSn(info.getSn());
            terDistribu.setAgentId(agentId);
            terDistribu.setState(2);
            terDistribu.setReceiveState(2);
            terDistribu.setDeptId(info.getDeptId());
            terDistribu.setDistribuTime(new Date());
            distribus.add(terDistribu);
        }
        baseMapper.insertDisList(distribus);

    }

    @Override
    public void handleNewSn(Long agentId, TerTerminalInfo info) {

        TerDistribu distribu = queryDistribuBySn(info.getSn());
        SysAgent baseAgent = agentService.queryBasicAgentBydeptId(info.getDeptId());
        if (baseAgent == null) {
            throw new RRException("9000", "未查询到平台账号");
        }
        if (distribu == null) {

            distribu = new TerDistribu();
            distribu.setAgentId(baseAgent.getAgentId());
            distribu.setDeptId(info.getDeptId());
            distribu.setState(1);
            distribu.setReceiveState(1);
            distribu.setToAid(agentId);
            distribu.setSn(info.getSn());
            distribu.setDistribuTime(new Date());
            insert(distribu);

            TerDistribu dis = new TerDistribu();
            dis.setAgentId(agentId);
            dis.setDeptId(info.getDeptId());
            dis.setState(2);
            dis.setReceiveState(2);
            dis.setSn(info.getSn());
            dis.setDistribuTime(new Date());
            insert(dis);
        } else {
            disTerminal(info.getSn(), agentId, info.getDeptId());
        }
    }


}

